package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Slf4j
@RestController
public class TemplateMessageController {
    @Resource
    private WxMpService wxMpService;

    @Resource
    private WxMpConfigStorage wxMpConfigStorage;

    @GetMapping("sendTemplateMessage")
    public String sendTemplateMessage() throws WxErrorException {
        log.info("accessToken: {}", wxMpConfigStorage.getAccessToken());
        // 创建模板消息，设置模板id、指定模板消息要发送的目标用户
        WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                .templateId("meNp7HCzs-PnIFhJEWd2fF9HNqzR5tsSMulT9CUBR_s")
                .toUser("o63YF52s67WW4SQ8_VkWqVwamN-4")
                .build();
        /*
         * 手机型号: {{goodsName.DATA}}
         * 时间: {{time.DATA}}
         * 价格: {{price.DATA}}
         * 备注: {{remark.DATA}}
         */
        // 填充模板消息中的变量
        wxMpTemplateMessage.addData(new WxMpTemplateData("goodsName", "华为mate40pro"));
        wxMpTemplateMessage.addData(new WxMpTemplateData("time", "2020-10-25"));
        wxMpTemplateMessage.addData(new WxMpTemplateData("price", "6999"));
        wxMpTemplateMessage.addData(new WxMpTemplateData("remark", "麒麟9000牛逼"));
        // 发送模板消息，返回消息id
        String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        log.info("accessToken: {}", wxMpConfigStorage.getAccessToken());
        return msgId;
    }
}
